package com.hg.order;

import com.hg.MqConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * created by skh on 2019/12/14
 */
@Data
@Slf4j
//注册到spring容器后,会自动注册消费者
//@Component
public class OrderConsumer {

	private DefaultMQPushConsumer consumer;

	@Autowired
	private OrderMessageListener orderMessageListener;

	@PostConstruct
	public void init() throws MQClientException {
		consumer = new DefaultMQPushConsumer(MqConfig.consumerGroup);
		consumer.setNamesrvAddr(MqConfig.nameServerAddr);
		consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
		consumer.subscribe(MqConfig.orderTopic, "*");
		consumer.registerMessageListener(orderMessageListener);
		consumer.start();
		log.info("消费者服务启动成功");
	}

	@PreDestroy
	public void destroy() {
		consumer.shutdown();
		log.info("消费者服务关闭成功");
	}
}
